<template>
  <el-row style="background-image: url('/static/background/background.png')">
    <el-row>
      <el-radio-group v-model='activeName' @change='handleRadioChange'>
        <el-radio-button label='1'>长期磋商</el-radio-button>
        <el-radio-button label='2'>短期磋商</el-radio-button>
      </el-radio-group>
    </el-row>
    <el-row>
      <el-col :span='16'>
        <div id='diagramParentDiv'>
          <div id='diagramDiv' style='width: 100%; height: 90vh' />
        </div>
      </el-col>
      <el-col :span='8' style='margin-top: 6%'>
        <bar-chart chartTitle='资源数量' :chartData='chartData' style='padding: 10px'></bar-chart>
        <bar-chart chartTitle='CPU配额' :chartData='chartDataCpu' style='padding: 10px'></bar-chart>
        <bar-chart chartTitle='内存配额' :chartData='chartDataMem' style='padding: 10px'></bar-chart>
      </el-col>
    </el-row>
  </el-row>
</template>

<script>
import request from '@/utils/request'
import BarChart from './components/chart.vue'
import bpmnModal from './bpmn/bpmnModal.vue'

export function getPrivateCloud() {
  return request({
    url: '/cloud/v1.0/datacenter/list?withDetail=false',
    method: 'get'
  })
}

export function getConsulList() {
  return request({
    url: '/cloud/jcce/v1.0/consult/list?pageNumber=1&pageSize=1000',
    method: 'get'
  })
}

export function getPublicCloud() {
  return request({
    url: '/cloud/pub/v1.0/cloud_platform?pageNo=1&pageSize=10000',
    method: 'get'
  })
}

export function getResourceCount(cloudType, id) {
  return request({
    url: '/cloud/jcce/v1.0/consult/cloudType/' + cloudType + '/id/' + id,
    // url: '/admin/api/sysRole/roleMenuTree' + '/' + role,
    method: 'get'
  })
}

import go from 'gojs'

export async function createConsult(cloudPlatformIds, privateIds) {
  return new Promise((resolve, reject) => {
    request({
      url: '/cloud/jcce/v1.0/consult/createConsult',
      method: 'post',
      params: {
        cloudPlatformIds: cloudPlatformIds,
        privatePlatformIds: privateIds
      }
    }).then((data) => {
      resolve(data)
    })
  })
}

export default {
  name: '',
  components: {
    BarChart,
    bpmnModal
  },
  data() {
    return {
      chartData: [100, 100],
      chartDataCpu: [100, 100],
      chartDataMem: [100, 100],
      consulResult: [],
      publicCloudList: [],
      privateCloudList: [],
      activeName: '1'
    }
  },
  mounted() {
    function getImage(node, map, type) {
      if (map[type + '_' + node.id] === undefined) {
        return require('@/static/OWFS_CLOSE.png')
      } else {
        if (type === 'public') {
          return require('@/static/OWFS.png')
        } else {
          return require('@/static/OWFS_DOWN.png')
        }
      }
    }

    const apis = [
      this.getPublicRes(),
      this.getPrivateRes(),
      this.getConsulResult()
    ]
    Promise.all(apis).then((res) => {
      this.nodes = []
      let keyMap = {}
      this.consulResult.forEach((item) => {
        // { key: 2, text: 'Main 2', isGroup: true, category: 'OfGroups' },
        const groupNode = {
          key: item.id,
          text: item.name.replace('+', '_'),
          isGroup: true,
          category: 'OfGroups'
        }
        this.nodes.push(groupNode)
        if (item.privatePlatformIds === null) {
          item.cloudPlatformIds.split(',').forEach((v) => {
            keyMap['public' + '_' + v] = item.id
          })
        }
        if (item.cloudPlatformIds === null) {
          item.privatePlatformIds.split(',').forEach((v) => {
            keyMap['private' + '_' + v] = item.id
          })
        }
      })

      this.publicCloudList.forEach((pNode) => {
        //  { text: 'first D', group: 6, key: -14 },
        let publicNode = {
          text: pNode.platformName,
          key: 'public' + '_' + pNode.id,
          source: getImage(pNode, keyMap, 'public')
        }
        if (keyMap['public' + '_' + pNode.id] !== undefined) {
          publicNode.group = keyMap['public' + '_' + pNode.id]
        }
        this.nodes.push(publicNode)
      })

      this.privateCloudList.forEach((pNode) => {
        let privateNode = {
          text: pNode.name,
          key: 'private' + '_' + pNode.id,
          source: getImage(pNode, keyMap, 'private')
        }
        if (keyMap['private' + '_' + pNode.id] !== undefined) {
          privateNode.group = keyMap['private' + '_' + pNode.id]
        }
        this.nodes.push(privateNode)
      })

      this.initGraph()
      console.log(keyMap)
    })
  },
  methods: {
    handleRadioChange(value) {
      if ("2" === value) {
        this.$router.push({ name: 'negotiate_bpmn', params: null })
      }
    },
    getConsulResult() {
      return new Promise((resolve, reject) => {
        getConsulList()
          .then((res) => {
            this.consulResult = res.data.pageData
            resolve()
          })
          .catch((e) => {
            reject(e)
          })
      })
    },
    getPublicRes() {
      return new Promise((resolve, reject) => {
        getPublicCloud()
          .then((res) => {
            this.publicCloudList = res.data.pageData
            resolve()
          })
          .catch((e) => {
            reject(e)
          })
      })
    },

    getPrivateRes() {
      return new Promise((resolve, reject) => {
        getPrivateCloud()
          .then((res) => {
            this.privateCloudList = res.data
            resolve()
          })
          .catch((e) => {
            reject(e)
          })
      })
    },
    async getGraphData() {
      let ids = this.selectedSupplier.map((s) => s.id).join(',')
      let privateIds = this.selectedPrivateSupplier
        .map((s) => s.id)
        .join(',')

      console.log('ids:' + ids)
      console.log('privateIds:' + privateIds)

      // 创建磋商任务
      let res = await createConsult(ids, privateIds)
      this.graphLinkData = res.data.graphLinkDataList
      this.graphData = res.data.graphDataList
    },
    async initGraph() {
      const self = this
      // await this.getGraphData()

      var $$ = go.GraphObject.make

      const links = []

      const mygoChart = document.getElementById('diagramDiv')
      console.log(mygoChart)
      const diagramParentDiv = document.getElementById('diagramParentDiv')
      diagramParentDiv.removeChild(mygoChart)
      const div = document.createElement('div')
      div.setAttribute('id', 'diagramDiv')
      div.setAttribute('style', 'width:100%; height:90vh')
      diagramParentDiv.appendChild(div)
      this.dataDiagram = $$(go.Diagram, 'diagramDiv', {
        // layout: $$(go.GridLayout)
        'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom,
        initialAutoScale: go.Diagram.Uniform,
        // start everything in the middle of the viewport
        initialContentAlignment: go.Spot.Center,
        // disable user copying of parts
        allowCopy: false,
        layout: $$(go.CircularLayout, {})
      })

      this.dataDiagram.groupTemplateMap.add(
        'OfGroups',
        $$(
          go.Group,
          'Auto',
          {
            background: 'transparent',
            // highlight when dragging into the Group
            computesBoundsAfterDrag: true,
            // when the selection is dropped into a Group, add the selected Parts into that Group;
            // if it fails, cancel the tool, rolling back any changes
            handlesDragDropForMembers: true, // don't need to define handlers on member Nodes and Links
            // Groups containing Groups lay out their members horizontally
            layout: $$(go.GridLayout, {
              wrappingWidth: Infinity,
              alignment: go.GridLayout.Position,
              cellSize: new go.Size(1, 1),
              spacing: new go.Size(4, 4)
            })
          },
          new go.Binding('background', 'isHighlighted', function(h) {
            return h ? 'rgba(255,0,0,0.2)' : 'transparent'
          }).ofObject(),
          $$(go.Shape, 'Rectangle', {
            fill: null,
            stroke: '#8dedf4',
            strokeWidth: 2
          }),
          $$(
            go.Panel,
            'Vertical', // title above Placeholder
            $$(
              go.Panel,
              'Horizontal', // button next to TextBlock
              {
                stretch: go.GraphObject.Horizontal,
                background: '#8dedf4'
              },
              $$('SubGraphExpanderButton', {
                alignment: go.Spot.Right,
                margin: 5
              }),
              $$(
                go.TextBlock,
                {
                  alignment: go.Spot.Left,
                  editable: true,
                  margin: 5,
                  font: 'bold 18px sans-serif',
                  opacity: 0.75,
                  stroke: '#404040'
                },
                new go.Binding('text', 'text').makeTwoWay()
              )
            ), // end Horizontal Panel
            $$(go.Placeholder, {
              padding: 5,
              alignment: go.Spot.TopLeft
            })
          ) // end Vertical Panel
        )
      ) // end Group and call to add to template Map

      this.dataDiagram.groupTemplateMap.add(
        'OfNodes',
        $$(
          go.Group,
          'Auto',
          {
            background: 'transparent',
            ungroupable: true,
            // highlight when dragging into the Group
            computesBoundsAfterDrag: true,
            // when the selection is dropped into a Group, add the selected Parts into that Group;
            // if it fails, cancel the tool, rolling back any changes
            handlesDragDropForMembers: true, // don't need to define handlers on member Nodes and Links
            // Groups containing Nodes lay out their members vertically
            layout: $$(go.GridLayout, {
              wrappingColumn: 1,
              alignment: go.GridLayout.Position,
              cellSize: new go.Size(1, 1),
              spacing: new go.Size(4, 4)
            })
          },
          new go.Binding('background', 'isHighlighted', function(h) {
            return h ? 'rgba(255,0,0,0.2)' : 'transparent'
          }).ofObject(),
          $$(go.Shape, 'Rectangle', {
            fill: null,
            stroke: '#33D3E5',
            strokeWidth: 2
          }),
          $$(
            go.Panel,
            'Vertical', // title above Placeholder
            $$(
              go.Panel,
              'Horizontal', // button next to TextBlock
              {
                stretch: go.GraphObject.Horizontal,
                background: '#33D3E5'
              },
              $$('SubGraphExpanderButton', {
                alignment: go.Spot.Right,
                margin: 5
              }),
              $$(
                go.TextBlock,
                {
                  alignment: go.Spot.Left,
                  editable: true,
                  margin: 5,
                  font: 'bold 16px sans-serif',
                  opacity: 0.75,
                  stroke: '#404040'
                },
                new go.Binding('text', 'text').makeTwoWay()
              )
            ), // end Horizontal Panel
            $$(go.Placeholder, {
              padding: 5,
              alignment: go.Spot.TopLeft
            })
          ) // end Vertical Panel
        )
      ) // end Group and call to add to template Map

      this.dataDiagram.nodeTemplate = $$(
        go.Node,
        'Vertical',
        {
          click: function(e, node) {
            let split = node.data.key.split('_')
            let cloudType = split[0]
            let cloudId = split[1]
            getResourceCount(cloudType, cloudId).then((res) => {
              self.chartData = [res.data[0], res.data[1]]
              self.chartDataCpu = [res.data[2], res.data[3]]
              self.chartDataMem = [res.data[4], res.data[5]]
              // resolve()
            }).catch((e) => {
              // reject(e)
            })
          }
        },
        $$(
          go.Panel,
          'Auto',
          $$(go.Shape, 'RoundedRectangle', {
            fill: null, // 设置内部填充的颜色
            stroke: 'rgba(255,255,255,0)' // 设置边框的颜色
          }),
          $$(
            go.Panel,
            'Table',
            $$(
              go.Picture,
              {
                row: 0,
                column: 0,
                rowSpan: 2,
                desiredSize: new go.Size(60, 60)
              },
              new go.Binding('source')
            ),
            $$(
              go.TextBlock,
              {
                row: 2,
                column: 0,
                rowSpan: 2,
                alignment: go.Spot.Top,
                margin: 5,
                font: 'bold 14px sans-serif ',
                stroke: '#ffffff'
              },
              new go.Binding('text')
            )
          )
        )
      )

      this.dataDiagram.model = new go.GraphLinksModel(this.nodes, links)
      console.log(this.nodes)
      this.linkLoop()
    },

    linkLoop() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        const oldskips = this.dataDiagram.skipsUndoManager
        this.dataDiagram.skipsUndoManager = true
        this.dataDiagram.links.each(function(link) {
          const shape = link.findObject('PIPE')
          const off = shape.strokeDashOffset - 2
          shape.strokeDashOffset = off <= 0 ? 20 : off
          // speed = parseInt(link.jb.flow);
        })
        this.dataDiagram.skipsUndoManager = oldskips
        this.linkLoop()
      }, 200)
    },
    // 概览列表
    consultList() {
      return request({
        url: '/cloud/jcce/v1.0/kt1/overview2',
        method: 'get'
      })
    }
  }
}
</script>

<style lang='scss'>
.el-tabs__header {
  padding: 0;
  position: relative;
  margin: 0 0 0px;
}

.el-tabs__item {
  font-size: 14px;
  color: #ffffff;
}
</style>
